package com.rcl.mvvmdemo.lifecycle

import android.util.Log

/**
 * 管理所注册进来的接口，这个接口就是ILifecycle
 * 保存当前view的生命周期状态
 */
class LifecycleProviders {

    private var currentLifecycleState: LifecycleState = LifecycleState.DESTROY
    private val lifecycleListener = arrayListOf<AbsLifecycle>()

    fun addLifecycleListener(lifecycle: AbsLifecycle) {
        if (!lifecycleListener.contains(lifecycle)) {
            lifecycleListener.add(lifecycle)
        }
    }

    fun removeLifecycleListener(lifecycle: AbsLifecycle) {
        lifecycleListener.remove(lifecycle)
    }

    fun makeLifecycleState(state: LifecycleState) {
        currentLifecycleState = state
        lifecycleListener.forEach {
            it.onViewLifeStateChange(state)
        }
        when (state) {
            LifecycleState.CREATE -> {
                dispatchCreateState()
            }

            LifecycleState.START -> {
                dispatchStartState()
            }

            LifecycleState.RESUME -> {
                dispatchResumeState()
            }

            LifecycleState.PAUSE -> {
                dispatchPauseState()
            }

            LifecycleState.STOP -> {
                dispatchStopState()
            }

            LifecycleState.DESTROY -> {
                dispatchDestroyState()
            }
        }
    }

    private fun dispatchCreateState() {
        lifecycleListener.forEach {
            it.onCreate()
        }
    }

    private fun dispatchStartState() {
        lifecycleListener.forEach {
            it.onStart()
        }
    }

    private fun dispatchResumeState() {
        lifecycleListener.forEach {
            it.onResume()
        }
    }

    private fun dispatchPauseState() {
        lifecycleListener.forEach {
            it.onPause()
        }
    }

    private fun dispatchStopState() {
        lifecycleListener.forEach {
            it.onStop()
        }
    }

    private fun dispatchDestroyState() {
        lifecycleListener.forEach {
            it.onDestroy()
        }
        lifecycleListener.clear()
    }

    fun isAtLeast(state: LifecycleState): Boolean {
        Log.i("aaaaa", "current State: ${currentLifecycleState} === ${state}")
        val isAsLestState = currentLifecycleState > state
        Log.i("aaaaa", "isAsLestState==>$isAsLestState")
        return isAsLestState
    }

}